package com.jiuwu.spring.eshop.controller;

import com.jiuwu.spring.eshop.db.entity.OrderEt;
import com.jiuwu.spring.eshop.respository.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Optional;

@Slf4j
@Controller
@RequestMapping("/manage")
public class OrderController {

    @Autowired
    OrderRepository orderRepository;

    @RequestMapping("/order_manage")
    public String getOrders(Model model){
        List<OrderEt> orders = orderRepository.findAll();
        model.addAttribute("orders",orders);
        return "/manage/order_manage";
    }

    @RequestMapping("/order_detail/{orderID}")
    public String detailOrder(@PathVariable("orderID")String orderId, Model model) {
        Integer id = Integer.valueOf(orderId);
        Optional<OrderEt> optionalOrderEt = orderRepository.findById(id);
        if (optionalOrderEt != null && optionalOrderEt.isPresent()) {
            OrderEt order= optionalOrderEt.get();
            model.addAttribute("order", order);
        }
        return "/manage/order_detail";
    }

    @RequestMapping("/order_enforce/{orderId}")
    public String enforceOrder(@PathVariable("orderId")String orderId){

        Integer id = Integer.valueOf(orderId);
        orderRepository.updateOrderInfo(id,1);
        return "redirect:/manage/index?id=3";
    }






    //------------------------------------thymeleaf-------------------------------------

    /**
     * 获取所有订单信息
     */
    @GetMapping(value = {"/orders","/orders/{pageNum}"})
    public String getOrders2(@PathVariable(value = "pageNum",required = false)Integer pageNum,Model model){
        pageNum = pageNum == null ? 0 : pageNum>0?pageNum-1:0;
        Page<OrderEt> orderPage = orderRepository.findAll(PageRequest.of(pageNum, 5));
        model.addAttribute("orderPage",orderPage);
        return "order";
    }

    @GetMapping("/order/{orderId}")
    public String toOrder(@PathVariable("orderId")String orderId, Model model){
        Integer id = Integer.valueOf(orderId);
        Optional<OrderEt> orderEtOptional = orderRepository.findById(id);
        if(orderEtOptional.isPresent()){
            OrderEt order  = orderEtOptional.get();  //切记勿传orderEtOptional，否则读不到实体属性
            model.addAttribute("order",order);
        }

        return "order/queryOrder";
    }
}
